package com.xj.qq.adapters;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;
import com.xj.qq.R;
import com.xj.qq.domain.Msg;

import java.util.List;

public class MsgAdapters extends RecyclerView.Adapter<MsgAdapters.ViewHolder> {

    private List<Msg> mMsgLIst;
    //内部类
    static class ViewHolder  extends  RecyclerView.ViewHolder{
        LinearLayout leftLayout;
        LinearLayout rightLayout;
        TextView  leftMsg;
        TextView  rightMsg;

        //找到子项布局中的控件
        public ViewHolder(View view){
            super(view);
            leftLayout = (LinearLayout) view.findViewById ( R.id.layout_left );
            rightLayout = (LinearLayout) view.findViewById ( R.id.layout_right );
            leftMsg = (TextView) view.findViewById ( R.id.left_msg );
            rightMsg = (TextView) view.findViewById ( R.id.right_msg );
        }
    }
    //构造函数，用于把要展示的数据源传递进来
    public  MsgAdapters(List<Msg>  msgLIst){
        mMsgLIst = msgLIst;
    }
    //加载子项布局，返回一个View
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent,int viewType){
        View view = LayoutInflater.from ( parent.getContext ())
                .inflate(R.layout.msg_item,parent,false);
        return new ViewHolder ( view );
    }
    //对子项中的数据赋值函数
    @Override
    public void onBindViewHolder(ViewHolder holder,int position){
        Msg msg = mMsgLIst.get ( position );//得到msg实例
        if (msg.getType()==Msg.TYPE_RECEIVED){//表示收到消息
            holder.leftLayout.setVisibility ( View.VISIBLE );//显示左边的消息布局
            holder.rightLayout.setVisibility ( View.GONE );//隐藏右边的消息布局
            holder.leftMsg.setText ( msg.getContent () );
        }else if (msg.getType()==Msg.TYPE_SENT){
            holder.rightLayout.setVisibility ( View.VISIBLE );
            holder.leftLayout.setVisibility ( View.GONE );
            holder.rightMsg.setText ( msg.getContent () );
        }
    }
    @Override
    public int getItemCount(){
        return mMsgLIst.size ();
    }
}
